# Copyright (C) 2007 Samuel Abels, http://debain.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
from Scope        import Scope
from Term         import Term
from String       import String
from Regex        import Regex
from FunctionCall import FunctionCall
from Variable     import Variable
import GrammarBody

class TokenList(Scope):
    def __init__(self, parser, parent):
        Scope.__init__(self, 'TokenList', parser, parent)
        self.tokens = []
        self.body   = None

        # Collect the token and variable names.
        while not parser.next_if('newline'):
            token = None
            alias = None

            # Parse the token.
            if parser.current_is('regex_delimiter'):
                token = Regex(parser, self)
            elif parser.current_is('varname'):
                token = Variable(parser, self)
                self.variable_test(token.varname)
            else:
                self.char = parser.current_char
                parent.unexpected_token_error(self, parser.token())

            # Parse the alias, if it was defined.
            if parser.next_if('colon'):
                if parser.next_if('minus'):
                    alias = '-'
                elif parser.current_is('string_delimiter'):
                    alias = String(parser, self).string
                    self.parent.define(**{alias: None})
                else:
                    self.char = parser.current_char
                    parent.unexpected_token_error(self, parser.token())

            self.tokens.append((token, alias))
            while parser.next_if('whitespace') or parser.next_if('newline'):
                pass

            # If the list has a body, parse it.
            if parser.next_if('semicolon'):
                break
            elif parser.next_if('open_curly_bracket'):
                self.body = GrammarBody.GrammarBody(parser, self)
                parser.expect(self, 'close_curly_bracket')
                break

        self.mark_end(parser)


    def dump(self, indent = 0):
        print (' ' * indent) + self.name, repr(self.input)
        for token, alias in self.tokens:
            print  (' ' * (indent + 1)) + 'Token: %s' % token
            print  (' ' * (indent + 2)) + 'Alias: %s' % alias
        if self.body is not None:
            self.body.dump(indent + 2)
